import 'dart:io';
import 'package:ball_lion/module/pick/items/banner_scaffold.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/mine/my_recharge_logic.dart';
import 'package:ball_lion/service/config_service.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/constant.dart';
import 'package:ball_lion/utils/regex_util.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/ads_label.dart';
import 'package:ball_lion/widgets/base/wqs_bottomsheet.dart';
import 'package:ball_lion/widgets/base/wqs_button.dart';
import 'package:ball_lion/module/pay/pay_bottom_sheet.dart';
import 'package:ball_lion/entity/pay/recharge_entity.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/circular.dart';
import 'my_web_page.dart';

class RechargePage extends StatefulWidget {
  const RechargePage({super.key}) : isSheet = false;

  const RechargePage.sheet({super.key}) : isSheet = true;

  final bool isSheet;

  @override
  State<RechargePage> createState() => _RechargePageState();
}

class _RechargePageState extends State<RechargePage> {
  late final MyRechargeLogic logic;
  final textController = TextEditingController();

  @override
  void initState() {
    logic = Get.put(MyRechargeLogic(isSheet: widget.isSheet));
    Get.find<ConfigService>().tipEnable = false;
    super.initState();
  }

  @override
  void dispose() {
    Get.find<ConfigService>().tipEnable = true;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return widget.isSheet ? _bottomSheet() : _page();
  }

  Widget _bottomSheet() {
    return QsBottomSheet(
        title: "球币充值",
        backIcon: "arrow_back.png",
        closeResult: false,
        child: GetBuilder<MyRechargeLogic>(builder: (logic) {
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Circular(
                  radius: 4,
                  color: Colours.white.withOpacity(0.1),
                  padding: const EdgeInsets.symmetric(vertical: 2),
                  child: Row(
                    children: [
                      Container(width: 4),
                      Image.asset(Utils.getImgPath("plan_coin.png"), width: 14),
                      Container(width: 4),
                      QsText(
                          "余额：${User.info?.gold == null ? '0' : User.info!.gold!.toStringAsFixed(2)}球币",
                          fontSize: 12,
                          color: Colours.grey66)
                    ],
                  )),
              _moneyGrid().paddingSymmetric(vertical: 12),
              QsButton(
                height: 44,
                width: Get.width,
                enable: logic.currentIndex != null,
                backgroundColor: Colours.main,
                foregroundColor: Colours.white,
                borderRadius: 8,
                onPressed: logic.pay,
                text: '充值',
              ).paddingSymmetric(vertical: 8),
              _agreement(),
              const SizedBox(height: 8)
            ],
          );
        }));
  }

  Widget _page() {
    return BannerScaffold(
      type: 'recharge',
      needScroll: false,
      bannerHeight: Get.width * 214 / 375,
      backFade: false,
      backColor: Colours.transparent,
      brightness: Brightness.light,
      titleWidget: Column(children: [
        const QsText('充值'),
        if (User.info?.phone != null && User.auth?.type == 1)
          QsText(
            '${User.info!.phone!.substring(0, 3)}****${User.info!.phone!.substring(7)}',
            color: Colours.white,
            fontSize: 10,
          )
      ]),
      action: [
        TextButton(
            onPressed: () {
              Utils.onEvent('charge_coin_detail');
              Get.toNamed(Routes.myCoinHistory);
            },
            child: const QsText('明细', color: Colours.white))
      ],
      aboveWidget: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const QsText("我的球币", color: Colours.white, fontSize: 12),
            QsText(
                User.info?.gold == null
                    ? '0'
                    : User.info!.gold!.toStringAsFixed(2),
                fontSize: 35,
                color: Colours.white,
                fontWeight: FontWeight.w500,
                height: 1.1)
          ]).paddingOnly(left: 16, bottom: 30),
      body: (physics) => Container(
        color: Colours.white,
        padding: const EdgeInsets.symmetric(horizontal: 16),
        child: GetBuilder<MyRechargeLogic>(
          initState: (_) {},
          builder: (_) {
            return SingleChildScrollView(
              child: Column(children: [
                const SizedBox(height: 24),
                _body().paddingOnly(bottom: 16),
                const AdsLabel(
                    adsTag: 'recharge',
                    width: 343,
                    margin: EdgeInsets.only(bottom: 16)),
                _rechargeInfo(),
              ]),
            );
          },
        ),
      ),
    );
  }

  Widget _body() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const QsText('球币充值', fontSize: 16, fontWeight: FontWeight.w500),
        const SizedBox(height: 12),
        _customMoney(),
        const SizedBox(height: 16),
        _moneyGrid(),
        Container(height: 8),
        Row(
          children: [
            GestureDetector(
              onTap: () => logic.onAgree(),
              behavior: HitTestBehavior.opaque,
              child: Padding(
                  padding: const EdgeInsets.fromLTRB(0, 8, 5, 8),
                  child: Image.asset(
                    Utils.getImgPath(logic.agree ? 'check.png' : 'uncheck.png'),
                    width: 12,
                    height: 12,
                  )),
            ),
            _agreement()
          ],
        ),
      ],
    );
  }

  Widget _customMoney() {
    return Row(
      children: [
        Expanded(
          child: SizedBox(
            height: 44,
            child: TextField(
              controller: textController,
              keyboardType: TextInputType.number,
              inputFormatters: [
                FilteringTextInputFormatter.allow(
                    (RegExp(RegexUtil.number9999)))
              ],
              onChanged: (value) {
                setState(() {});
              },
              onTap: () => Utils.onEvent('cz', params: {'cz': '2'}),
              onTapOutside: (event) {
                FocusScope.of(context).unfocus();
              },
              decoration: InputDecoration(
                fillColor: Colours.greyF8F8FA,
                filled: true,
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(4),
                    borderSide: BorderSide.none),
                contentPadding:
                    const EdgeInsets.symmetric(horizontal: 16, vertical: 2),
                hintText: "自定义金额1元至9999元",
                hintStyle: const TextStyle(fontSize: 14, color: Colours.grey99),
              ),
            ),
          ),
        ),
        const SizedBox(width: 8),
        QsButton(
          height: 44,
          width: 109,
          backgroundColor: Colours.main,
          foregroundColor: Colours.white,
          borderRadius: 4,
          onPressed: () async {
            FocusScope.of(context).requestFocus(FocusNode());
            if (textController.text.isEmpty) {
              Toast.text('请输入金额');
              return;
            }
            if (!logic.agree) {
              Toast.text('请先同意《用户充值协议》');
              return;
            }
            Utils.onEvent('cz', params: {'cz': '3'});
            final mode = await Get.bottomSheet(PayBottomSheet.recharge(
                price: textController.text,
                gold: textController.text.toDouble() ?? 0));
            if (mode != null) {
              logic.generateOrder(
                  payAmt: double.parse(textController.text)
                      .toStringAsFixed(2)
                      .toDouble(),
                  payMode: mode);
            }
          },
          text: '充值',
        ),
      ],
    );
  }

  Widget _moneyGrid() {
    return Wrap(
      spacing: 8,
      runSpacing: 6,
      children: List.generate(logic.list.length, (index) => _moneyCard(index)),
    );
  }

  _moneyCard(index) {
    RechargeEntity data = logic.list[index];
    return GestureDetector(
      onTap: () async {
        if (!widget.isSheet) {
          Utils.onEvent('cz', params: {'cz': '${index + 3}'});
          if (!logic.agree) {
            Toast.text('请先同意《用户充值协议》');
            return;
          }
        }
        logic.currentIndex = index;
        if (!widget.isSheet) logic.pay();
      },
      child: SizedBox(
        height: 84,
        child: Stack(
          alignment: Alignment.bottomLeft,
          children: [
            Container(
              width: (Get.width - 49) / 3,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4),
                  color: logic.currentIndex != index
                      ? Colours.greyF5F7FA
                      : Colours.main.withOpacity(0.1),
                  border: logic.currentIndex != index
                      ? null
                      : Border.all(
                          color: Colours.main,
                          width: 0.5,
                          strokeAlign: BorderSide.strokeAlignInside)),
              height: 80,
              child: Column(children: [
                const SizedBox(height: 12),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    QsText(data.gold!.toStringAsFixed(0),
                        fontSize: 19,
                        color: logic.currentIndex != index
                            ? Colours.text
                            : Colours.main,
                        fontWeight: FontWeight.w500),
                    const SizedBox(width: 4),
                    QsText('球币',
                        fontSize: 13,
                        color: logic.currentIndex != index
                            ? Colours.text
                            : Colours.main)
                  ],
                ),
                QsText(data.content ?? "", fontSize: 10, color: Colours.main),
                Container(height: 2),
                QsText('￥${data.payAmt!.toStringAsFixed(2)}',
                    fontSize: 13,
                    fontWeight: FontWeight.w500,
                    color: logic.currentIndex != index
                        ? Colours.grey66
                        : Colours.main)
              ]),
            ),
            if (data.tag.hasValue)
              Positioned(
                top: 0,
                child: Container(
                  height: 14,
                  padding: const EdgeInsets.symmetric(horizontal: 8),
                  alignment: Alignment.center,
                  clipBehavior: Clip.antiAlias,
                  decoration: const BoxDecoration(
                      color: Colours.main,
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(20),
                          topRight: Radius.circular(50),
                          bottomRight: Radius.circular(50))),
                  child: QsText(data.tag ?? "",
                      needCenter: true, fontSize: 10, color: Colours.white),
                ),
              ),
          ],
        ),
      ),
    );
  }

  _agreement() {
    return RichText(
        text: TextSpan(children: [
      const TextSpan(
          text: '充值即代表您已同意',
          style: TextStyle(color: Colours.grey99, fontSize: 12)),
      TextSpan(
          text: '《用户充值协议》',
          style: const TextStyle(color: Colours.main, fontSize: 12),
          recognizer: TapGestureRecognizer()
            ..onTap = () {
              Get.toNamed(Routes.webview,
                  arguments: WebPara(Constant.payPolicyUrl, longpress: false));
            }),
    ]));
  }

  _rechargeInfo() {
    if (Platform.isAndroid) {
      return RichText(
          text: TextSpan(children: [
        const TextSpan(
            text: '1. 球狮体育',
            style: TextStyle(color: Colours.grey99, fontSize: 12)),
        const TextSpan(
            text: '非购彩平台', style: TextStyle(color: Colours.main, fontSize: 12)),
        const TextSpan(
            text: '，球币一经充值成功，只可用于购买平台内容付费服务，',
            style: TextStyle(color: Colours.grey99, fontSize: 12)),
        const TextSpan(
            text: '不支持提现、购彩等操作',
            style: TextStyle(color: Colours.main, fontSize: 12)),
        const TextSpan(
            text: '；\n2.若球币充值和消费过程中遇到问题，请',
            style: TextStyle(color: Colours.grey99, fontSize: 12)),
        TextSpan(
            text: '联系客服',
            style: const TextStyle(color: Colours.blue2766D6, fontSize: 12),
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                Get.toNamed(Routes.myContact);
              }),
        const TextSpan(
            text: '进行反馈。',
            style: TextStyle(color: Colours.grey99, fontSize: 12)),
      ]));
    } else {
      return RichText(
          text: TextSpan(children: [
        const TextSpan(
            text: '1. 球狮体育',
            style: TextStyle(color: Colours.grey99, fontSize: 12)),
        const TextSpan(
            text: '非购彩平台', style: TextStyle(color: Colours.main, fontSize: 12)),
        const TextSpan(
            text: '，球币一经充值成功，只可用于购买平台内容付费服务，',
            style: TextStyle(color: Colours.grey99, fontSize: 12)),
        const TextSpan(
            text: '不支持提现、购彩等操作',
            style: TextStyle(color: Colours.main, fontSize: 12)),
        const TextSpan(
            text:
                '；\n2. 购买球币为AppStore应用内购买，所使用的Apple ID必须与下载球狮体育APP时使用的Apple ID一致；\n3. 如遇到苹果支付问题，建议App Store绑定支付宝(App Store-App栏目底部-快速链接-绑定支付宝)；\n',
            style: TextStyle(color: Colours.grey99, fontSize: 12)),
        TextSpan(
            text: '4. 若球币充值和消费过程中遇到问题，请',
            style: const TextStyle(color: Colours.grey99, fontSize: 12),
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                Get.toNamed(Routes.myContact);
              }),
        TextSpan(
            text: '联系客服',
            style: const TextStyle(color: Colours.blue2766D6, fontSize: 12),
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                Get.toNamed(Routes.myContact);
              }),
        TextSpan(
            text: '进行反馈。',
            style: const TextStyle(color: Colours.grey99, fontSize: 12),
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                Get.toNamed(Routes.myContact);
              }),
      ]));
    }
  }
}
